package com.EAsystem.service.Impl;

import com.EAsystem.entity.Leave;
import com.EAsystem.mapper.LeaveMapper;
import com.EAsystem.service.LeaveService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 请假管理Service实现类
 */
@Service
public class LeaveServiceImpl implements LeaveService {

    @Autowired
    private LeaveMapper leaveMapper;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public boolean addLeave(Leave leave) {
        // 设置初始状态为待审批
        leave.setStatus(0);
        // 设置创建和更新时间
        String now = sdf.format(new Date());
        leave.setCreateTime(now);
        leave.setUpdateTime(now);
        return leaveMapper.insertLeave(leave) > 0;
    }

    @Override
    public boolean updateLeave(Leave leave) {
        // 设置更新时间
        leave.setUpdateTime(sdf.format(new Date()));
        return leaveMapper.updateLeave(leave) > 0;
    }

    @Override
    public boolean deleteLeave(Integer id) {
        return leaveMapper.deleteLeaveById(id) > 0;
    }

    @Override
    public Leave getLeaveById(Integer id) {
        return leaveMapper.findLeaveById(id);
    }



    @Override
    public List<Leave> getLeavesByStudentId(Integer studentId) {
        return leaveMapper.findLeavesByStudentId(studentId);
    }



    @Override
    public PageInfo<Leave> getAllLeavesWithPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Leave> leaves = leaveMapper.findAllLeavesWithPage();
        return new PageInfo<>(leaves);
    }

    @Override
    public PageInfo<Leave> getLeavesByConditionWithPage(Leave leave, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Leave> leaves = leaveMapper.findLeavesByCondition(leave);
        return new PageInfo<>(leaves);
    }

    @Override
    public boolean approveLeave(Integer id, Integer status) {
        // 状态只能是已批准(1)或已拒绝(2)
        if (status != 1 && status != 2) {
            return false;
        }
        String updateTime = sdf.format(new Date());
        return leaveMapper.approveLeave(id, status, updateTime) > 0;
    }

    @Override
    public PageInfo<Leave> getLeavesByTeacherWithPage(Integer teacherId, Long courseId, Integer status, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Leave> leaves = leaveMapper.findLeavesByTeacher(teacherId, courseId, status);
        return new PageInfo<>(leaves);
    }
}